package com.good.webadmin.Service.impl;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.good.webadmin.Models.Audience;
import com.good.webadmin.Models.TokenUser;
import com.good.webadmin.Service.IJavaWebTokenService;
import com.good.webadmin.config.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Service
public class JavaWebTokenServiceImpl implements IJavaWebTokenService {

    @Autowired
    private Audience audience;

    /**
     * 根据用户名称生成签名
     * @param userId
     * @param userName
     * @return token
     */
    @Override
    public String sign(String userId,String userName){
        if(StringUtils.isEmpty(userId)){
            log.error(" userId is null ");
            return null;
        }
        if(StringUtils.isEmpty(userName)){
            log.error(" userName is null ");
            return null;
        }

        long eTime =audience.getExpiresSecond()*1000;
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + eTime);
            token = JWT.create()
                    .withIssuer(userId)
                    .withClaim("data", userName)
                    .withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(audience.getSecretKey()));
          } catch (Exception e){
            e.printStackTrace();
            throw new MyException(401,e.getMessage());
        }
        return token;

    }

    /**
     * 签名验证
     * @param userId
     * @param token
     * @return true or false
     */
    @Override
    public TokenUser verify(String userId, String token) {
        if(StringUtils.isEmpty(userId)){
            log.error(" userId is null ");
            throw  new MyException(401," userId is null");
        }
        if(StringUtils.isEmpty(token)){
            log.error(" token is null ");
            throw  new MyException(401,"token is null");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(audience.getSecretKey())).withIssuer(userId).build();

            DecodedJWT jwt = verifier.verify(token);
            TokenUser tokenUser = new TokenUser();
            tokenUser.setUserId(Long.valueOf(jwt.getIssuer()));
            tokenUser.setNickName(jwt.getClaim("data").asString());
            return tokenUser;
        } catch (Exception e){
            e.printStackTrace();
            throw  new MyException(401,e.getMessage());
//            throw e;
        }

    }



}


